<template>
  <div>
    <div>
      <el-card class="elcard">
        <el-form>
          <el-form-item>
            <el-input width="60px" class="input-width" v-model="username" />
            <el-button
              icon="el-icon-search"
              type="primary"
              @click="selectUserInfo"
              >查询</el-button
            >
            <el-button @click="clearSelect">清空</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="dialogFormVisible = true"
              >添加</el-button
            >
            <el-button type="danger" disabled>批量删除</el-button>
          </el-form-item>
        </el-form>
        <el-table style="width: 100%" border :data="UserList" class="Spu-table">
          <el-table-column type="selection" width="55" />
          <el-table-column label="序号" type="index" width="60" center />
          <el-table-column label="用户名" prop="username" />
          <el-table-column label="用户昵称" prop="nickName" />
          <el-table-column label="角色列表" prop="roleName" />
          <el-table-column label="创建时间" prop="gmtCreate" />
          <el-table-column label="更新时间" prop="gmtModified" />
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-button
                type="info"
                @click="toSetAssign(row)"
                icon="el-icon-user"
                size="small"
              />
              <el-button
                type="primary"
                @click="EditUserInfo(row)"
                icon="el-icon-edit"
                size="small"
              />
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="DelUserInfo(row)"
                style="margin-left: 10px"
              >
                <el-button
                  type="danger"
                  slot="reference"
                  icon="el-icon-delete"
                  size="small"
                />
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="limit"
          layout=" prev, pager, next, jumper ,->,total, sizes"
          :total="total"
          class="pagination-div"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
    </div>
    <el-dialog
      @closed="clearID"
      title="添加用户"
      :visible.sync="dialogFormVisible"
    >
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="用户名" prop="username" label-width="120px">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" label-width="120px">
          <el-input v-model="form.nickName"></el-input>
        </el-form-item>
        <el-form-item
          label="用户密码"
          v-if="!form.id"
          prop="password"
          label-width="120px"
        >
          <el-input v-model="form.password"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clearDialog">取 消</el-button>
        <el-button type="primary" @click="SaveUserInfo">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      @open="openDialogAssign"
      title="设置角色"
      :visible.sync="dialogSetUser"
    >
      <el-form :model="setUser">
        <el-form-item label="用户名" label-width="80px">
          <el-input :value="setUser.roleName" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色列表" label-width="80px">
          <template>
            <el-checkbox
              :indeterminate="isIndeterminate"
              v-model="checkAll"
              @change="handleCheckAllChange"
              >全选</el-checkbox
            >
            <div style="margin: 15px 0"></div>
            <el-checkbox-group
              v-model="assignRoles"
              @change="handleCheckedCitiesChange"
            >
              <el-checkbox
                v-for="roleKey in allRolesKey"
                :label="roleKey.id"
                :key="roleKey.id"
                >{{ roleKey.roleName }}</el-checkbox
              >
            </el-checkbox-group>
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogSetUser = false">取 消</el-button>
        <el-button type="primary" @click="SaveUserAssign">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  DelUserInfoApi,
  getToAssignApi,
  getUserInfoListApi,
  SaveUserAssignApi,
  SaveUserInfoApi,
  updateUserInfoApi
} from '@/api/UserApi'

export default {
  name: 'User',
  data() {
    return {
      // 当前页码
      page: 1,
      // 每页多少条
      limit: 5,
      total: 100,
      username: '',
      UserList: [],
      dialogFormVisible: false,
      form: {
        username: '',
        nickName: '',
        password: '',
        id: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      setUser: {
        roleName: '',
        id: ''
      },
      dialogSetUser: false,
      assignRoles: [],
      allRolesKey: [],
      checkAll: false,
      isIndeterminate: true
    }
  },
  methods: {
    async getUserList() {
      const res = await getUserInfoListApi(this.page, this.limit, this.username)
      if (res.code === 20000) {
        this.total = res.data.total
        this.UserList = res.data.items
      }
    },
    handleSizeChange(val) {
      this.limit = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getUserList()
    },
    selectUserInfo() {
      if (!this.username) return
      this.getUserList()
    },
    clearSelect() {
      this.username = ''
      this.getUserList()
    },
    async SaveUserInfo() {
      await this.$refs.ruleForm.validate()
      let res = {}
      if (this.form.id) {
        res = await updateUserInfoApi({
          ...this.form
        })
      } else {
        res = await SaveUserInfoApi(this.form)
      }

      if (res.code === 20000) {
        this.dialogFormVisible = false
        this.getUserList()
        this.form.username = ''
        this.form.nickName = ''
        this.form.password = ''
      }
    },
    async DelUserInfo(row) {
      const res = await DelUserInfoApi(row.id)
      if (res.code === 20000) {
        this.$message.success('删除成功')
        this.getUserList()
      }
    },
    EditUserInfo(row) {
      this.form = { ...row }
      this.dialogFormVisible = true
    },
    clearDialog() {
      this.dialogFormVisible = false
      this.form.username = ''
      this.form.nickName = ''
      this.form.password = ''
    },
    clearID() {
      this.form.id = ''
    },
    async toSetAssign(row) {
      const res = await getToAssignApi(row.id)
      if (res.code === 20000) {
        this.assignRoles = res.data.assignRoles.map((item) => item.id)
        this.setUser.roleName = row.username
        this.setUser.id = row.id
        this.allRolesKey = res.data.allRolesList.map((item) => {
          return { roleName: item.roleName, id: item.id }
        })
        this.dialogSetUser = true
      }
    },
    handleCheckAllChange(val) {
      this.isIndeterminate = false
      this.assignRoles = val ? this.allRolesKey.map((item) => item.id) : []
    },
    handleCheckedCitiesChange(value) {
      this.assignRoles = value
      if (this.assignRoles.length !== this.allRolesKey.length) {
        this.isIndeterminate = true
        if (!this.assignRoles.length) {
          this.checkAll = false
          this.isIndeterminate = false
        }
      }
      if (this.assignRoles.length === this.allRolesKey.length) {
        this.checkAll = true
        this.isIndeterminate = false
      }
    },
    openDialogAssign() {
      if (this.assignRoles.length !== this.allRolesKey.length) {
        this.isIndeterminate = true
        if (!this.assignRoles.length) {
          this.checkAll = false
          this.isIndeterminate = false
        }
      } else {
        this.isIndeterminate = false
        this.checkAll = true
      }
    },
    async SaveUserAssign() {
      let userId = this.setUser.id
      let roleId = this.assignRoles.join(',')
      const res = await SaveUserAssignApi(userId, roleId)
      if (res.code === 20000) {
        this.dialogSetUser = false
        this.getUserList()
        this.$message.success('分配角色成功')
      }
    }
  },
  mounted() {
    this.getUserList()
  }
}
</script>

<style scoped>
.elcard {
  margin: 20px;
}
.input-width {
  width: 200px;
  margin-right: 10px;
}

.pagination-div {
  margin-top: 20px;
}
</style>
